// 专辑Service

import 'dart:io';

import '../dao/dao_user_album.dart';
import '../dao/dao_user_album_media.dart';
import '../dao/dao_user_album_media_record.dart';
import '../model/model_user_album.dart';
import '../model/model_user_album_media.dart';
import '../tools/tools_subtitle.dart';

class ServiceUserAlbum {
  // 添加
  static Future<bool> add(String path) async {
    print('ServiceUserAlbum.add()');

    // 1. 文件夹信息处理

    ModelUserAlbum m = new ModelUserAlbum();
    m.name = path.substring(path.lastIndexOf("/") + 1);
    m.filePath = path;

    // 判断是否已存在
    ModelUserAlbum? m3 = await DaoUserAlbum.findByPath(path);
    if (m3 != null) {
      print("已存在,不添加");
      return false;
    }

    // 遍历子文件
    Stream<FileSystemEntity> fileList = Directory(path).list();
    List<ModelUserAlbumMedia> ms = [];
    Set<String> wordSetAll = new Set();
    num speedAll = 0;
    int sentenceQtyAll = 0;
    int mediaQty = 0;
    await for (FileSystemEntity fileSystemEntity in fileList) {
      print('$fileSystemEntity');

      ModelUserAlbumMedia muam = new ModelUserAlbumMedia();
      String filePath = fileSystemEntity.path;
      muam.fileName = filePath!.substring(filePath!.lastIndexOf("/") + 1);
      if (muam.fileName!.lastIndexOf(".") != -1) {
        String subName = muam.fileName!.substring(muam.fileName!.lastIndexOf("."));
        if (subName == ".mp4" || subName == ".mp3") {
          print(muam);
          mediaQty++;

          String srtPath = filePath!.substring(0, filePath!.lastIndexOf("/") + 1);
          srtPath += muam.fileName!.substring(0, muam.fileName!.lastIndexOf("."));
          srtPath += ".srt";
          print(srtPath);

          File srtFile = new File(srtPath);
          if (await srtFile.exists()) {
            try {
              String srtContent = srtFile.readAsStringSync();
              // print(srtContent);
              var tmpL = ToolsSubtitle.analysisSrtContent(srtContent);
              print(tmpL);
              muam.sentenceQty = tmpL[0];
              sentenceQtyAll += muam.sentenceQty!;
              muam.wordQty = tmpL[1];
              muam.speed = tmpL[2];

              for (String s in tmpL[3]) {
                wordSetAll.add(s);
              }
              // wordSetAll.addAll(tmpL[3]);
              speedAll += tmpL[2];
            } on Exception catch (err) {
              print("读取srt出错," + err.toString());
            }
          }

          ms.add(muam);
        }
      }
    }
    m.mediaQty = mediaQty;
    if (ms.length > 0) {
      m.speed = speedAll ~/ ms.length;
    } else {
      m.speed = 0;
    }
    m.sentenceQty = sentenceQtyAll;
    m.wordQty = wordSetAll.length;

    // 2. 保存到本地sqlite
    DaoUserAlbum.insert(m);
    ModelUserAlbum? m2 = await DaoUserAlbum.findByName(m.name!);
    if (m2 != null) {
      print(m2!.id);
      for (ModelUserAlbumMedia me in ms) {
        me.userAlbumId = m2!.id;
        DaoUserAlbumMedia.insert(me);
      }
    } else {
      print("错误:没找到条目,为什么?");
    }

    // 3. 请求服务器api保存

    return true;
  }

  // 删除
  static Future<void> deleteById(int id) async {
    // 删除Album
    await DaoUserAlbum.deleteById(id);
    // 删除Album下media
    await DaoUserAlbumMedia.deleteByAlbumId(id);
    // 删除所有相关记录
    await DaoUserAlbumMediaRecord.deleteByAlbumId(id);
  }

  // 修改
  static bool updateById(ModelUserAlbum a) {
    return true;
  }

  static Future<void> updateUserAlbumPath(int id, String selectedDirectory) async {
    ModelUserAlbum? album = await DaoUserAlbum.findById(id);
    if (album != null) {
      album!.filePath = selectedDirectory;
      await DaoUserAlbum.updateById(album);
      // List<ModelUserAlbumMedia> list = await DaoUserAlbumMedia.findAllByAlbumId(id);
      // for (ModelUserAlbumMedia m in list) {}
    }
  }

  // 查询
  static Future<List<ModelUserAlbum>> list() async {
    List<ModelUserAlbum> list = await DaoUserAlbum.findAll();
    return list;
  }
}
